﻿var webStorage = {};
webStorage.webSql = function () {

    var _this = this;

    this.d = [];

    //数据库
    var _dataBase;

    //打开数据库连接或者创建数据库
    this.openDatabase = function () {

        if (!!_dataBase) {
            return _dataBase;
        }
        _dataBase = openDatabase("bookDB", "1.0", "Books information", 1024 * 1024, function () { });

        return _dataBase;
    }

    //创建数据表
    this.createTable = function () {

        var dataBase = _this.openDatabase();
        // 创建表
        dataBase.transaction(function (tx) {
            tx.executeSql(
        "create table if not exists books (id REAL UNIQUE, name TEXT, date TEXT, money TEXT)", [],
        function () {
            //alert('创建book表成功'); 
        },
        function (tx, error) {
            //alert('创建book表失败:' + error.message);
        });
        });
    }

    //添加数据
    this.insert = function (obj) {
        var dataBase = _this.openDatabase();
        dataBase.transaction(function (tx) {
            tx.executeSql(
        "insert into books (id, name, date, money) values(?, ?, ?, ?)",
        [obj.id, obj.name, obj.date, obj.money],
        function () {

        },
        function (tx, error) {
            alert('添加数据失败: ' + error.message);
        });
        });

    }

    // 查询
    this.query = function (callback) {
        var dataBase = _this.openDatabase();
        dataBase.transaction(function (tx) {
            tx.executeSql(
        "select * from books", [],
         function (tx, result) {
             _this.d = result.rows;
         },
        function (tx, error) {
            alert('查询失败: ' + error.message);
        });
        });
    }

    //更新数据
    this.update = function (obj) {
        var dataBase = _this.openDatabase();
        dataBase.transaction(function (tx) {
            tx.executeSql(
        "update books set name = ?,date=?,money=? where id= ?",
        [obj.name, obj.date, obj.money, obj.id],
         function (tx, result) {
         },
        function (tx, error) {
            alert('更新失败: ' + error.message);
        });
        });
    }

    //删除数据
    this.delItem = function (obj) {
        var dataBase = _this.openDatabase();
        dataBase.transaction(function (tx) {
            tx.executeSql(
        "delete from books where id= ?",
        [obj.id],
         function (tx, result) {

         },
        function (tx, error) {
            alert('删除失败: ' + error.message);
        });
        });
    }

    //删除数据表
    this.dropTable = function () {
        var dataBase = _this.openDatabase();
        dataBase.transaction(function (tx) {
            tx.executeSql('drop  table  books');
        });
    }


}